#include "stdafx.h";
#include "SixAxisController.h"

JOYINFOEX GetJOYINFOEX(void);

SixAxisController::SixAxisController(void)
{
	try
	{
		joystickInfo = GetJOYINFOEX();
		axisX = (float)(joystickInfo.dwXpos - 32767.0f) / 32768;
		axisY = (float)(joystickInfo.dwYpos - 32767.0f) / 32768;
		axisZ = (float)(joystickInfo.dwZpos - 32767.0f) / 32768;
		axisR = (float)(joystickInfo.dwRpos - 32767.0f) / 32768;

		if (axisX < .1f && axisX > -.1f)
			axisX = 0.0f;
		if (axisY < .1f && axisY > -.1f)
			axisY = 0.0f;
		if (axisZ < .1f && axisZ > -.1f)
			axisZ = 0.0f;
		if (axisR < .1f && axisR > -.1f)
			axisR = 0.0f;
	}
	catch(const char*)
	{
		axisX = axisY = axisZ = axisR = 0.0f;
		joystickInfo.dwPOV = 0.0f;
	}
}

SixAxisController::~SixAxisController(void)
{
}

JOYINFOEX GetJOYINFOEX(void)
{
	JOYINFOEX joystickInfo;
	ZeroMemory(&joystickInfo, sizeof(joystickInfo));
	joystickInfo.dwSize = sizeof(joystickInfo);
	joystickInfo.dwFlags |= JOY_RETURNALL;
	if (joyGetPosEx(JOYSTICKID1, &joystickInfo) != JOYERR_NOERROR)
	{
		throw "No JoyStick Available";
	}
	return joystickInfo;
}

SixAxisController* SixAxisController::GetCurrentState(void)
{
	return new SixAxisController();
}

bool SixAxisController::IsButtonPressed(int btn)
{
	return (joystickInfo.dwButtons & btn) == btn;
}

bool SixAxisController::IsDPadPressed(int btn)
{
	return joystickInfo.dwPOV == btn;
}

Vector2 SixAxisController::GetLeftAnalog()
{
	Vector2 left = { axisX, axisY };
	return left;
}

Vector2 SixAxisController::GetRightAnalog()
{
	Vector2 right = { axisZ, axisR };
	return right;
}
